"use server"
import {ActionState} from "@/lib/zod/types";
import {CreateUserSchema, EditUserSchema, UserOmitCreatedAtPartial} from "@/lib/zod/schema";
import db from "@/lib/db";
import {z} from "zod";
import {hmacEncode} from "@/lib/password";


export const editOrCreateUser = async (_state: ActionState<z.infer<typeof UserOmitCreatedAtPartial>>, formData: FormData) => {
    const entries = Object.fromEntries(formData.entries());

    const ModeSchema = z.object({mode: z.enum(['add', 'edit'])});
    const modeSchema = ModeSchema.safeParse(entries);
    if (!modeSchema.success) {
        return {
            code:402,
            msg:"参数校验异常,必须声明表单提交模式",
        }
    }

    if (modeSchema.data.mode ==='edit') {
        const editUserSchema = EditUserSchema.safeParse(entries);

        if (!editUserSchema.success) {
            const errors = editUserSchema.error.flatten().fieldErrors;
            return {
                code:402,
                msg:"参数校验异常",
                errors: errors,
                input:{
                    ...entries
                }
            }
        }

        try{
            const {userId, password, ...user} = editUserSchema.data;

            if (password != '000000'){
                //用户修改了密码
                const   passwordStr = hmacEncode(password,process.env.USER_LOGIN_PASSWORD_SECRET!);
                await db.users.update({
                    data: {...user, password: passwordStr},
                    where: {
                        userId: userId
                    }
                })
            }
            //没有修改密码
            await db.users.update({
                data: user,
                where: {
                    userId: userId
                }
            })
        }catch {
            return {
                code:500,
                msg:"系统异常",
                input:{
                    ...editUserSchema.data
                }
            }
        }
    }

    if(modeSchema.data.mode==='add'){
        const createUserSchema = CreateUserSchema.safeParse({...entries, createdAt: new Date()});
        if (!createUserSchema.success) {
            const errors = createUserSchema.error.flatten().fieldErrors;
            return {
                code:402,
                msg:"参数校验异常",
                errors: errors,
                input:{
                    ...entries
                }
            }
        }
        const {password,...user} = createUserSchema.data;
        try {
            //如果不存在id则为创建
            const   passwordStr = hmacEncode(password,process.env.USER_LOGIN_PASSWORD_SECRET!);
            await db.users.create({
                data: {password: passwordStr,image:"/image/default-avatar.jpeg", ...user},
            })
        }catch {
            return {
                code:500,
                msg:"系统异常",
                input:{
                    password,
                    ...user
                }
            }
        }
    }


    return {
        code: 200,
        msg: "操作成功",
    };
}